#include "csvtools.h"


csvtools2::csvtools2(std::string csvname, std::string header, bool autofile, bool newfile)
{
    _csvname = csvname;
    _header_str = header;
    _autofile = autofile;
    _newfile = newfile;
    create_file();
}

csvtools2::~csvtools2()
{
    _srcFile.close();
}

void csvtools2::addrow(std::string row)
{
    _srcFile << row.c_str() << endl;

    if (++_addindex_nums >= _maxnums)
    {
        create_file();
        _addindex_nums = 0;
    }
}

void csvtools2::set_max_nums(int max)
{
    _maxnums = max;
}

void csvtools2::create_file()
{
    _have_file_nums++;
    std::string tmpfile;
    if (_autofile)
    {
        tmpfile = _csvname + std::string("_") + std::to_string(_have_file_nums) + ".csv";
    }
    else
    {
        tmpfile = _csvname + ".csv";
    }

    if (_srcFile.is_open())
    {
        _srcFile.close();
    }
    if (_newfile)
    {
        _srcFile.open(tmpfile, ios::out | ios::trunc);
    }
    else
    {
        _srcFile.open(tmpfile, ios::out | ios::app);
    }
    
    if ( !_srcFile.is_open()) {
        cout << "error opening source file." << endl;
        throw "error opening source file.";
    }
    if (_header_str.size() > 0)
    {
        _srcFile << _header_str.c_str() << endl;
    }
}
